<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::section})}">

<head>
    <title>图书详情 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>图书详情</h2>
            <div>
                <a th:href="@{/book/edit/{id}(id=${book.id})}" class="btn btn-primary">
                    <i class="fas fa-edit"></i> 编辑
                </a>
                <a href="/book/list" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
            </div>
        </div>

        <div class="row">
            <!-- 图书信息 -->
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">基本信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <img th:src="${book.coverImage != null ? book.coverImage : '/images/default-book.jpg'}"
                                    th:alt="${book.name}" class="img-fluid rounded" style="max-height: 300px;">
                            </div>
                            <div class="col-md-8">
                                <h3 th:text="${book.name}">图书名称</h3>
                                <p class="text-muted">
                                    <span th:text="${book.author}">作者</span> 著
                                </p>
                                <table class="table table-borderless">
                                    <tbody>
                                        <tr>
                                            <th scope="row" style="width: 100px;">ISBN</th>
                                            <td th:text="${book.isbn}">ISBN</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">分类</th>
                                            <td th:text="${book.categoryName}">分类</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">出版社</th>
                                            <td th:text="${book.publisher}">出版社</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">出版日期</th>
                                            <td th:text="${#temporals.format(book.publishDate, 'yyyy-MM-dd')}">出版日期</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">价格</th>
                                            <td th:text="${'¥' + book.price}">价格</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">库存</th>
                                            <td>
                                                <span th:text="${book.stock}">库存</span>
                                                <button class="btn btn-sm btn-outline-primary ml-2" id="updateStockBtn">
                                                    <i class="fas fa-edit"></i> 修改库存
                                                </button>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">位置</th>
                                            <td th:text="${book.location}">位置</td>
                                        </tr>
                                        <tr>
                                            <th scope="row">状态</th>
                                            <td>
                                                <span
                                                    th:class="${book.status == 1 ? 'badge badge-success' : 'badge badge-danger'}"
                                                    th:text="${book.status == 1 ? '上架' : '下架'}">状态</span>
                                                <button class="btn btn-sm btn-outline-primary ml-2"
                                                    id="toggleStatusBtn">
                                                    <i class="fas fa-exchange-alt"></i>
                                                    <span th:text="${book.status == 1 ? '下架' : '上架'}">切换状态</span>
                                                </button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 图书描述 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">图书描述</h5>
                    </div>
                    <div class="card-body">
                        <p th:text="${book.description}">图书描述</p>
                    </div>
                </div>

                <!-- 图书评论 -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">图书评论</h5>
                        <button class="btn btn-sm btn-primary" id="addCommentBtn">
                            <i class="fas fa-plus"></i> 添加评论
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="commentList">
                            <!-- 评论将通过AJAX加载 -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 借阅记录 -->
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">借阅记录</h5>
                        <button class="btn btn-sm btn-primary" id="borrowBookBtn">
                            <i class="fas fa-plus"></i> 借阅此书
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="borrowRecordList">
                            <!-- 借阅记录将通过AJAX加载 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 修改库存模态框 -->
        <div class="modal fade" id="updateStockModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">修改库存</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="updateStockForm">
                            <div class="form-group">
                                <label for="stock">库存数量</label>
                                <input type="number" class="form-control" id="stock" name="stock" min="0"
                                    th:value="${book.stock}" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveStockBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加评论模态框 -->
        <div class="modal fade" id="addCommentModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">添加评论</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="addCommentForm">
                            <div class="form-group">
                                <label for="userId">用户</label>
                                <select class="form-control" id="userId" name="userId" required>
                                    <!-- 用户列表将通过AJAX加载 -->
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="rating">评分</label>
                                <select class="form-control" id="rating" name="rating" required>
                                    <option value="5">5星</option>
                                    <option value="4">4星</option>
                                    <option value="3">3星</option>
                                    <option value="2">2星</option>
                                    <option value="1">1星</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="content">评论内容</label>
                                <textarea class="form-control" id="content" name="content" rows="3" required></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveCommentBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 借阅图书模态框 -->
        <div class="modal fade" id="borrowBookModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">借阅图书</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="borrowBookForm">
                            <div class="form-group">
                                <label for="borrowUserId">借阅用户</label>
                                <select class="form-control" id="borrowUserId" name="userId" required>
                                    <!-- 用户列表将通过AJAX加载 -->
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="expectedReturnTime">预计归还时间</label>
                                <input type="date" class="form-control" id="expectedReturnTime"
                                    name="expectedReturnTime" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveBorrowBtn">借阅</button>
                    </div>
                </div>
            </div>
        </div>

        <script th:inline="javascript">
            $(document).ready(function () {
                // 获取图书ID
                const bookId = [[${ book.id }]];

                // 加载评论
                loadComments();

                // 加载借阅记录
                loadBorrowRecords();

                // 加载用户列表
                loadUsers();

                // 修改库存按钮点击事件
                $('#updateStockBtn').click(function () {
                    $('#updateStockModal').modal('show');
                });

                // 保存库存按钮点击事件
                $('#saveStockBtn').click(function () {
                    const stock = $('#stock').val();

                    $.ajax({
                        url: '/book/api/updateStock',
                        type: 'PUT',
                        data: {
                            id: bookId,
                            stock: stock
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                alert('库存修改成功！');
                                location.reload();
                            } else {
                                alert('库存修改失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 切换状态按钮点击事件
                $('#toggleStatusBtn').click(function () {
                    const currentStatus = [[${ book.status }]];
                    const newStatus = currentStatus === 1 ? 0 : 1;

                    $.ajax({
                        url: '/book/api/update',
                        type: 'PUT',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            id: bookId,
                            status: newStatus
                        }),
                        success: function (res) {
                            if (res.code === 200) {
                                alert('状态修改成功！');
                                location.reload();
                            } else {
                                alert('状态修改失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 添加评论按钮点击事件
                $('#addCommentBtn').click(function () {
                    $('#addCommentModal').modal('show');
                });

                // 保存评论按钮点击事件
                $('#saveCommentBtn').click(function () {
                    const userId = $('#userId').val();
                    const rating = $('#rating').val();
                    const content = $('#content').val();

                    $.ajax({
                        url: '/comment/api/add',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            userId: userId,
                            bookId: bookId,
                            rating: rating,
                            content: content,
                            status: 1
                        }),
                        success: function (res) {
                            if (res.code === 200) {
                                alert('评论添加成功！');
                                $('#addCommentModal').modal('hide');
                                loadComments();
                            } else {
                                alert('评论添加失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 借阅图书按钮点击事件
                $('#borrowBookBtn').click(function () {
                    // 设置默认归还时间为14天后
                    const today = new Date();
                    const returnDate = new Date(today);
                    returnDate.setDate(today.getDate() + 14);
                    $('#expectedReturnTime').val(returnDate.toISOString().split('T')[0]);

                    $('#borrowBookModal').modal('show');
                });

                // 保存借阅按钮点击事件
                $('#saveBorrowBtn').click(function () {
                    const userId = $('#borrowUserId').val();
                    const expectedReturnTime = $('#expectedReturnTime').val();

                    $.ajax({
                        url: '/borrow/api/borrow',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            userId: userId,
                            bookId: bookId,
                            expectedReturnTime: expectedReturnTime + 'T00:00:00'
                        }),
                        success: function (res) {
                            if (res.code === 200) {
                                alert('借阅成功！');
                                $('#borrowBookModal').modal('hide');
                                loadBorrowRecords();
                                location.reload(); // 刷新页面更新库存
                            } else {
                                alert('借阅失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 加载评论函数
                function loadComments() {
                    $.ajax({
                        url: '/comment/api/listByBookId/' + bookId,
                        type: 'GET',
                        success: function (res) {
                            if (res.code === 200) {
                                renderComments(res.data);
                            } else {
                                alert('获取评论失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }

                // 渲染评论函数
                function renderComments(comments) {
                    let html = '';

                    if (comments && comments.length > 0) {
                        for (let i = 0; i < comments.length; i++) {
                            const comment = comments[i];
                            const stars = '★'.repeat(comment.rating) + '☆'.repeat(5 - comment.rating);

                            html += `
                                <div class="media mb-3">
                                    <div class="media-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="mt-0">${comment.userName}</h5>
                                            <span class="text-warning">${stars}</span>
                                        </div>
                                        <p>${comment.content}</p>
                                        <small class="text-muted">${new Date(comment.createTime).toLocaleString()}</small>
                                    </div>
                                </div>
                            `;

                            if (i < comments.length - 1) {
                                html += '<hr>';
                            }
                        }
                    } else {
                        html = '<p class="text-center text-muted">暂无评论</p>';
                    }

                    $('#commentList').html(html);
                }

                // 加载借阅记录函数
                function loadBorrowRecords() {
                    $.ajax({
                        url: '/borrow/api/listByBookId/' + bookId,
                        type: 'GET',
                        success: function (res) {
                            if (res.code === 200) {
                                renderBorrowRecords(res.data);
                            } else {
                                alert('获取借阅记录失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }

                // 渲染借阅记录函数
                function renderBorrowRecords(records) {
                    let html = '';

                    if (records && records.length > 0) {
                        html = '<div class="list-group">';

                        for (let i = 0; i < records.length; i++) {
                            const record = records[i];
                            let statusText = '';
                            let statusClass = '';

                            switch (record.status) {
                                case 0:
                                    statusText = '已取消';
                                    statusClass = 'badge-secondary';
                                    break;
                                case 1:
                                    statusText = '借阅中';
                                    statusClass = 'badge-primary';
                                    break;
                                case 2:
                                    statusText = '已归还';
                                    statusClass = 'badge-success';
                                    break;
                                case 3:
                                    statusText = '已逾期';
                                    statusClass = 'badge-danger';
                                    break;
                            }

                            html += `
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h5 class="mb-1">${record.userName}</h5>
                                        <small>
                                            <span class="badge ${statusClass}">${statusText}</span>
                                        </small>
                                    </div>
                                    <p class="mb-1">
                                        借阅时间：${new Date(record.borrowTime).toLocaleString()}
                                    </p>
                                    <p class="mb-1">
                                        预计归还：${new Date(record.expectedReturnTime).toLocaleDateString()}
                                    </p>
                                    ${record.actualReturnTime ?
                                    `<p class="mb-1">实际归还：${new Date(record.actualReturnTime).toLocaleDateString()}</p>` : ''}
                                    ${record.status === 1 ?
                                    `<div class="mt-2">
                                            <button class="btn btn-sm btn-success" onclick="returnBook(${record.id})">
                                                <i class="fas fa-undo"></i> 归还
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="cancelBorrow(${record.id})">
                                                <i class="fas fa-times"></i> 取消
                                            </button>
                                        </div>` : ''}
                                </div>
                            `;
                        }

                        html += '</div>';
                    } else {
                        html = '<p class="text-center text-muted">暂无借阅记录</p>';
                    }

                    $('#borrowRecordList').html(html);
                }

                // 加载用户列表函数
                function loadUsers() {
                    $.ajax({
                        url: '/user/api/list',
                        type: 'GET',
                        data: {
                            pageNum: 1,
                            pageSize: 100
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                const users = res.data.list;
                                let html = '';

                                for (let i = 0; i < users.length; i++) {
                                    const user = users[i];
                                    html += `<option value="${user.id}">${user.name} (${user.username})</option>`;
                                }

                                $('#userId').html(html);
                                $('#borrowUserId').html(html);
                            } else {
                                alert('获取用户列表失败：' + res.message);
                            }
                        },
                        error: function () {
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }

                // 归还图书函数
                window.returnBook = function (id) {
                    if (confirm('确定归还这本图书吗？')) {
                        $.ajax({
                            url: '/borrow/api/return/' + id,
                            type: 'PUT',
                            success: function (res) {
                                if (res.code === 200) {
                                    alert('归还成功！');
                                    loadBorrowRecords();
                                    location.reload(); // 刷新页面更新库存
                                } else {
                                    alert('归还失败：' + res.message);
                                }
                            },
                            error: function () {
                                alert('服务器错误，请稍后再试！');
                            }
                        });
                    }
                };

                // 取消借阅函数
                window.cancelBorrow = function (id) {
                    if (confirm('确定取消这条借阅记录吗？')) {
                        $.ajax({
                            url: '/borrow/api/cancel/' + id,
                            type: 'PUT',
                            success: function (res) {
                                if (res.code === 200) {
                                    alert('取消成功！');
                                    loadBorrowRecords();
                                    location.reload(); // 刷新页面更新库存
                                } else {
                                    alert('取消失败：' + res.message);
                                }
                            },
                            error: function () {
                                alert('服务器错误，请稍后再试！');
                            }
                        });
                    }
                };
            });
        </script>
    </section>
</body>

</html>